#include "MGUI_Engine.h"

namespace Myway {

	MGUI_Engine * MGUI_Engine::msInstance = NULL;

	MGUI_Engine::MGUI_Engine(int w, int h)
	{
		msInstance = this;

		mRect = MGUI_Rect(0, 0, w, h);

		mHelper = new MGUI_Helper;

		mFontManager.Load("MGUI_Font.ini");
		mLookFeelManager.Load("MGUI_LookFeel.ini");
	}

	MGUI_Engine::~MGUI_Engine()
	{
		RemoveAllLayout();

		delete mHelper;

		msInstance = NULL;
	}

	// Layout
	void MGUI_Engine::AddLayout(MGUI_Layout * _layout)
	{
		mLayouts.PushFront(_layout);
	}

	void MGUI_Engine::RemoveLayout(MGUI_Layout * _layout)
	{
		for (int i = 0; i < mLayouts.Size(); ++i)
		{
			if (mLayouts[i] == _layout)
			{
				mLayouts.Erase(i);
				return ;
			}
		}

		d_assert (0);
	}

	void MGUI_Engine::RemoveAllLayout(bool _delete)
	{
		if (_delete)
		{
			for (int i = 0; i < mLayouts.Size(); ++i)
				delete mLayouts[i];
		}
		
		mLayouts.Clear();
	}


	MGUI_Layout * MGUI_Engine::GetLayout(const TString128 & name)
	{
		for (int i = 0; i < mLayouts.Size(); ++i)
		{
			if (mLayouts[i]->GetName() == name)
				return mLayouts[i];
		}

		return NULL;
	}


	void MGUI_Engine::OnResize(int w, int h)
	{
		mRect = MGUI_Rect(0, 0, w, h);
	}

	void MGUI_Engine::Update()
	{
		mInputManager.Update();

		for (int i = 0; i < mLayouts.Size(); ++i)
		{
			mLayouts[i]->Update();
		}
	}

	void MGUI_Engine::Render()
	{
		for (int i = 0; i < mLayouts.Size(); ++i)
		{
			if (mLayouts[i]->GetVisible())
			{
				mLayouts[i]->UpdateRenderItem();
				mLayouts[i]->DoRender();
			}
		}
	}

	MGUI_Widget * MGUI_Engine::GetWidget(int _x, int _y)
	{
		for (int i = mLayouts.Size() - 1; i >= 0; --i)
		{
			MGUI_Widget * item = mLayouts[i]->Pick(_x, _y);

			if (item)
				return item;
		}

		return NULL;
	}


	struct __sorter
	{
		bool operator()(MGUI_Layout * a, MGUI_Layout * b) const
		{
			return a->GetOrder() < b->GetOrder();
		}
	};

	void MGUI_Engine::NotifySortLayout()
	{
		Sort(&mLayouts[0], mLayouts.Size(), __sorter());
	}
}